/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.facebook.fresco.helper.utils;

import ohos.aafwk.ability.Ability;
import ohos.app.Context;
import ohos.app.Environment;
import ohos.data.usage.DataUsage;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.media.image.PixelMap;

import com.oszc.bbhmlibrary.wrapper.TextUtils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.UUID;

/**
 * 文件工具类
 *
 * @author dev
 * @since 2021-08-04
 */
public class FileUtils {
    /**
     * 标签
     */
    public static final String TAG = "FileUtils";

    /**
     * 拍照或者从相册选取，照片在本地的存储目录
     */
    public static final String IMAGE_CAMERA_UPLOAD_PATH = "/Photo/Upload";

    /**
     * LOG文件存放的目录
     */
    public static final String LOG_PATH = "/Log";

    /**
     * 语音文件存放的目录
     */
    public static final String VOICE_PATH = "/Voice";

    /**
     * 下载图片文件存放的目录
     */
    public static final String IMAGE_DOWNLOAD_IMAGES_PATH = "/Download/Images/";

    /**
     * 下载文件存放的目录
     */
    public static final String IMAGE_DOWNLOAD_PATH = "/Download/";

    /**
     * 下载分享图片文件存放的目录
     */
    public static final String IMAGE_SHARE_IMAGES_PATH = "/Download/ShareImages/";

    /**
     * tmp临时存放文件夹
     */
    public static final String TMP_PATH = "/Tmp";
    /**
     * 应用程序相关文件存放的根目录
     */
    private static final String ROOT_DIR_NAME = "CMoney";
    /**
     * 拍摄视频存放路径
     */
    private static final String VIDEO_DIR_PATH = "/Video/";

    /**
     * 视频文件缓存目录
     */
    private static final String VIDEO_CACHE_DIR = "/Video/cache";

    /**
     * 压缩视频存放路径
     */
    private static final String COMPRESS_VIDEO_DIR_PATH = "/CompressVideo/";

    /**
     * 压缩图片存在的目录
     */
    private static final String COMPRESS_DIR_PATH = "/Compress/";

    /**
     * 磁盘缓存目录
     */
    private static final String DISK_CACHE_DIR = "/DiskCache";

    /**
     * 礼物缓存目录
     */
    private static final String GIFT_CACHE_DIR = "/gift";

    /**
     * App web 缓存目录
     */
    private static final String WEB_CACHE_DIR = "/WebCache";

    /**
     * OCR（身份证、行驶证、银行卡、人脸识别得到的照片）临时文件存储目录
     */
    private static final String OCR_DIR = "/ORC/";

    private FileUtils() {
    }

    /**
     * 得到ocr文件
     *
     * @param context 上下文
     * @return {@link String}
     */
    public static String getOcrFile(Context context) {
        String rootDir = FileUtils.getRootDir(context);
        File dir = new File(rootDir + File.separator + FileUtils.OCR_DIR);
        if (!dir.exists()) {
            boolean mkdirs = dir.mkdirs();
        }

        String fileName = "ocr_pic.jpg";
        return dir + File.separator + fileName;
    }

    /**
     * 获取web缓存dir
     *
     * @param context 上下文
     * @return {@link String}
     */
    public static String getWebCacheDir(Context context) {
        String rootDir = FileUtils.getRootDir(context);
        if (!TextUtils.isEmpty(rootDir)) {
            File dir = new File(rootDir + File.separator + FileUtils.WEB_CACHE_DIR);
            if (!dir.exists()) {
                boolean mkdirs = dir.mkdirs();
            }
            try {
                return dir.getCanonicalPath();
            } catch (IOException error) {
                MLog.error("FileUtils getWebCacheDir " + error.getLocalizedMessage());
            }
        }
        return null; // 返回空
    }

    /**
     * 得到礼物目录
     *
     * @param context 上下文
     * @return {@link String}
     */
    public static String getGiftDirectory(Context context) {
        String rootDir = FileUtils.getRootDir(context);
        File dir = new File(rootDir + GIFT_CACHE_DIR);
        if (!dir.exists()) {
            boolean mkdirs = dir.mkdirs();
        }
        String path = "";
        try {
            path = dir.getCanonicalPath() + "/";
        } catch (IOException error) {
            MLog.error("FileUtils getGiftDirectory " + error.getLocalizedMessage());
        }
        return path;
    }

    /**
     * 获取缓存目录
     *
     * @param context 上下文
     * @return {@link File}
     */
    public static File getCacheDirectory(Context context) {
        String rootDir = FileUtils.getRootDir(context);
        File dir = new File(rootDir + DISK_CACHE_DIR);
        if (!dir.exists()) {
            boolean mkdirs = dir.mkdirs();
        }
        return dir;
    }

    /**
     * 获取视频文件所存放的目录
     *
     * @param context 上下文
     * @return {@link String}
     */
    public static String getVideoDir(Context context) {
        String rootDir = FileUtils.getRootDir(context);
        File dir = new File(rootDir + File.separator + FileUtils.VIDEO_DIR_PATH);
        if (!dir.exists()) {
            boolean mkdirs = dir.mkdirs();
        }
        String path = "";
        try {
            return dir.getCanonicalPath() + "/";
        } catch (IOException error) {
            MLog.error("FileUtils getVideoDir " + error.getLocalizedMessage());
        }
        return path;
    }

    /**
     * 得到视频缓存dir
     *
     * @param context 上下文
     * @return {@link File}
     */
    public static File getVideoCacheDir(Context context) {
        String rootDir = FileUtils.getRootDir(context);
        File dir = new File(rootDir + File.separator + FileUtils.VIDEO_CACHE_DIR);
        if (!dir.exists()) {
            boolean mkdirs = dir.mkdirs();
        }
        return dir;
    }

    /**
     * 获取压缩后的图片文件所存放的目录
     *
     * @param context 上下文
     * @return {@link String}
     */
    public static String getCompressImageDir(Context context) {
        String rootDir = FileUtils.getRootDir(context);
        File dir = new File(rootDir + File.separator + FileUtils.COMPRESS_DIR_PATH);
        if (!dir.exists()) {
            boolean mkdirs = dir.mkdirs();
        }
        String path = "";
        try {
            return dir.getCanonicalPath() + "/";
        } catch (IOException error) {
            MLog.error("FileUtils getCompressImageDir " + error.getLocalizedMessage());
        }
        return path;
    }

    /**
     * 获取视频文件所存放的目录
     *
     * @param context 上下文
     * @return {@link String}
     */
    public static String getCompressVideoDir(Context context) {
        String rootDir = FileUtils.getRootDir(context);
        File dir = new File(rootDir + File.separator + FileUtils.COMPRESS_VIDEO_DIR_PATH);
        if (!dir.exists()) {
            boolean mkdirs = dir.mkdirs();
        }
        String path = "";
        try {
            return dir.getCanonicalPath() + "/";
        } catch (IOException error) {
            MLog.error("FileUtils getCompressVideoDir " + error.getLocalizedMessage());
        }
        return path;
    }

    /**
     * 获取语音文件所存放的目录
     *
     * @param context 上下文
     * @return {@link String}
     */
    public static String getVoiceDir(Context context) {
        String rootDir = FileUtils.getRootDir(context);
        if (!TextUtils.isEmpty(rootDir)) {
            File dir = new File(rootDir + File.separator + FileUtils.VOICE_PATH);
            if (!dir.exists()) {
                boolean mkdirs = dir.mkdirs();
            }
            try {
                return dir.getCanonicalPath();
            } catch (IOException error) {
                MLog.error("FileUtils getVoiceDir " + error.getLocalizedMessage());
            }
        }
        return null;
    }

    /**
     * 获取语音文件名
     *
     * @param uid uid
     * @return {@link String}
     */
    public static String getVoiceFileName(String uid) {
        return uid + System.currentTimeMillis() + ".mp3";
    }

    /**
     * 存在的声音文件
     *
     * @param context 上下文
     * @param fileName 文件名称
     * @return boolean
     */
    public static boolean existsVoiceFile(Context context, String fileName) {
        String filePath = getVoiceDir(context) + File.separator + fileName;
        MLog.info("filePath = " + filePath);
        return exists(filePath);
    }

    /**
     * 存在
     *
     * @param filePath 文件路径
     * @return boolean
     */
    public static boolean exists(String filePath) {
        File file = new File(filePath);
        MLog.info(TAG, "检查本地是否存在 file = " + file.getPath());
        return file.exists() && file.isFile();
    }

    /**
     * 获取要上传的图片的路径
     *
     * @param context 上下文
     * @return {@link String}
     */
    public static String getUploadPhotoPath(Context context) {
        String rootDir = FileUtils.getRootDir(context);
        File dir = new File(rootDir + File.separator + FileUtils.IMAGE_CAMERA_UPLOAD_PATH);
        if (!dir.exists()) {
            boolean mkdirs = dir.mkdirs();
        }

        String fileName = UUID.randomUUID().toString() + ".jpg";
        return dir + File.separator + fileName;
    }

    /**
     * 获取图片路径
     *
     * @param context 上下文
     * @return {@link File}
     */
    public static File getPhotoPath(Context context) {
        String rootDir = FileUtils.getRootDir(context);
        File dir = new File(rootDir + File.separator + FileUtils.IMAGE_CAMERA_UPLOAD_PATH);
        if (!dir.exists()) {
            boolean mkdirs = dir.mkdirs();
        }

        try {
            return File.createTempFile("IMG_", ".jpg", dir);
        } catch (IOException error) {
            MLog.error("getPhotoPath IOException " + error.getLocalizedMessage());
        }

        String fileName = UUID.randomUUID().toString() + ".jpg";
        String path = dir + File.separator + fileName;
        return new File(path);
    }

    /**
     * 得到上传照片dir
     *
     * @param context 上下文
     * @return {@link String}
     */
    public static String getUploadPhotoDir(Context context) {
        String rootDir = FileUtils.getRootDir(context);
        File dir = new File(rootDir + File.separator + FileUtils.IMAGE_CAMERA_UPLOAD_PATH);
        if (!dir.exists()) {
            boolean mkdirs = dir.mkdirs();
        }
        String path = "";
        try {
            return dir.getCanonicalPath() + "/";
        } catch (IOException error) {
            MLog.error("FileUtils getUploadPhotoDir " + error.getLocalizedMessage());
        }
        return path;
    }

    /**
     * 得到图像下载dir
     *
     * @param context 上下文
     * @return {@link String}
     */
    public static String getImageDownloadDir(Context context) {
        String imageRootDir = getRootDir(context) + IMAGE_DOWNLOAD_IMAGES_PATH;
        File dir = new File(imageRootDir);
        if (!dir.exists()) {
            boolean mkdirs = dir.mkdirs();
        }
        String path = "";
        try {
            return dir.getCanonicalPath() + "/";
        } catch (IOException error) {
            MLog.error("FileUtils getImageDownloadDir " + error.getLocalizedMessage());
        }
        return path;
    }

    /**
     * 分享图片下载dir
     *
     * @param context 上下文
     * @return {@link String}
     */
    public static String getShareImageDownloadDir(Context context) {
        String imageRootDir = getRootDir(context) + IMAGE_SHARE_IMAGES_PATH;
        File dir = new File(imageRootDir);
        if (!dir.exists()) {
            boolean mkdirs = dir.mkdirs();
        }
        String path = "";
        try {
            return dir.getCanonicalPath() + "/";
        } catch (IOException error) {
            MLog.error("FileUtils getShareImageDownloadDir " + error.getLocalizedMessage());
        }
        return path;
    }


    /**
     * 得到图像qrcode路径
     *
     * @param ability 能力
     * @return {@link String}
     */
    public static String getImageQRCodePath(Ability ability) {
        String filePath = "";
        try {
            filePath = ability.getExternalFilesDir("").getCanonicalPath() + "/DCIM/Camera";
        } catch (IOException error) {
            MLog.error("FileUtils getImageQRCodePath " + error.getLocalizedMessage());
        }
        File dir = new File(filePath);
        if (!dir.exists()) {
            boolean mkdirs = dir.mkdirs();
        }
        return dir + File.separator + "qrCodeImage.jpg";
    }

    /**
     * 得到tmp dir
     *
     * @param context 上下文
     * @param fileName 文件名称
     * @return {@link String}
     */
    public static String getTmpDir(Context context, String fileName) {
        String imageRootDir = getRootDir(context) + TMP_PATH;
        File dir = new File(imageRootDir);
        if (!dir.exists()) {
            boolean mkdirs = dir.mkdirs();
        }
        String path ="";
        try {
            path =  dir.getCanonicalPath() + File.separator + fileName;
        } catch (IOException error) {
            MLog.error("FileUtils getTmpDir " + error.getLocalizedMessage());
        }
        return path;
    }

    /**
     * 获得临时dir
     *
     * @param context 上下文
     * @return {@link String}
     */
    public static String getTempDir(Context context) {
        String imageRootDir = getRootDir(context) + TMP_PATH;
        File dir = new File(imageRootDir);
        if (!dir.exists()) {
            boolean mkdirs = dir.mkdirs();
        }
        String path ="";
        try {
            path =  dir.getCanonicalPath() + File.separator;
        } catch (IOException error) {
            MLog.error("FileUtils getTmpDir " + error.getLocalizedMessage());
        }
        return path;
    }

    /**
     * 获取日志路径dir
     *
     * @param context 上下文
     * @param fileName 文件名称
     * @return {@link String}
     */
    public static String getLogPathDir(Context context, String fileName) {
        String rootDir = FileUtils.getRootDir(context);
        File dir = new File(rootDir + File.separator + LOG_PATH);
        if (!dir.exists()) {
            boolean mkdirs = dir.mkdirs();
        }
        return dir + File.separator + fileName;
    }

    /**
     * 获取外部存储路径
     * <p>
     *
     * @param context Context
     * @return SDCard卡或者手机内存的根路径
     */
    public static String getRootDir(Context context) {
        String cachePath = null;
        if (Environment.DIRECTORY_DOCUMENTS.equals(DataUsage.getDiskMountedStatus())) {
            // 外部存储可用
            File cacheFile = context.getExternalFilesDir(ROOT_DIR_NAME);
            if (cacheFile != null && cacheFile.exists()) {
                cachePath = cacheFile.getPath();
            }
            MLog.info(TAG, "getExternalFilesDir: " + cachePath);
        }

        if (TextUtils.isEmpty(cachePath)) {
            // 外部存储不可用
            cachePath = context.getFilesDir().getPath();
            MLog.info(TAG, "getFilesDir cachePath: " + cachePath);
        }
        return cachePath;
    }

    /**
     * 得到图像下载路径
     *
     * @param context 上下文
     * @return {@link String}
     */
    public static String getImageDownloadPath(Context context) {
        String imageRootDir = FileUtils.getImageDownloadDir(context);
        String fileName = UUID.randomUUID().toString() + ".jpg";
        return imageRootDir + File.separator + fileName;
    }

    /**
     * 分享图片下载路径
     *
     * @param context 上下文
     * @return {@link String}
     */
    public static String getShareImageDownloadPath(Context context) {
        String imageRootDir = FileUtils.getShareImageDownloadDir(context);
        String fileName = UUID.randomUUID().toString() + ".jpg";
        return imageRootDir + File.separator + fileName;
    }

    /**
     * 获取文件名称
     *
     * @return {@link String}
     */
    public static String getFileName() {
        String fileName = UUID.randomUUID().toString() + ".jpg";
        return fileName;
    }

    /**
     * 获取文件名称
     *
     * @param url url
     * @return {@link String}
     */
    public static String getFileName(String url) {
        String fileName = url.substring(url.lastIndexOf(File.separator) + 1);
        MLog.info(TAG, "fileName = " + fileName);
        return fileName;
    }

    /**
     * 得到下载路径
     *
     * @param context 上下文
     * @param url url
     * @return {@link String}
     */
    public static String getDownloadPath(Context context, String url) {
        if (url.startsWith("/")) {
            return url;
        }

        String fileName = getFileName(url);
        String imageRootDir = getRootDir(context) + IMAGE_DOWNLOAD_IMAGES_PATH;
        File dir = new File(imageRootDir);
        if (!dir.exists()) {
            boolean mkdirs = dir.mkdirs();
        }

        return dir + File.separator + fileName;
    }

    /**
     * 获取文件路径
     *
     * @param context 上下文
     * @param fileName 文件名称
     * @return {@link String}
     */
    public static String getFilePath(Context context, String fileName) {
        String imageRootDir = getRootDir(context) + IMAGE_DOWNLOAD_PATH;
        File dir = new File(imageRootDir);
        if (!dir.exists()) {
            boolean mkdirs = dir.mkdirs();
        }
        return dir + File.separator + fileName;
    }

    /**
     * 写文件
     *
     * @param context 上下文
     * @param bitmap 位图
     * @return {@link String}
     * @throws IOException ioexception
     */
    public static String writeFile(Context context, PixelMap bitmap) throws IOException {
        String photoPath = getImageDownloadPath(context);
        byte[] data = IOUtils.read(bitmap);
        IOUtils.write(photoPath, data);
        return photoPath;
    }

    /**
     * 清晰的
     *
     * @param context 上下文
     * @param dirPath dir路径
     */
    public static void clear(Context context, String dirPath) {
        String rootDir = FileUtils.getRootDir(context);
        File dir = new File(rootDir + File.separator + dirPath);
        if (dir.exists()) {
            File[] files = dir.listFiles();
            for (File f : files) {
                boolean delete = f.delete();
            }
        }
    }

    /**
     * 清除所有
     *
     * @param context 上下文
     */
    public static void clearAll(final Context context) {
        EventHandler eventHandler = new EventHandler(EventRunner.create());
        eventHandler.postTask(new Runnable() {
            @Override
            public void run() {
                String rootDir = FileUtils.getRootDir(context);
                File f = new File(rootDir);
                if (f.exists()) {
                    delFilesInOneDirectory(f);
                }
            }
        });
    }

    /**
     * del文件在一个目录中
     *
     * @param file 文件
     */
    public static void delFilesInOneDirectory(File file) {
        if (file.isFile()) {
            return;
        }
        if (file.isDirectory()) {
            File[] childFiles = file.listFiles();
            for (File f : childFiles) {
                if (f.isDirectory()) {
                    delFilesInOneDirectory(f);
                } else if (f.isFile()) {
                    boolean delete = f.delete();
                }
            }
        }

    }

    /**
     * 获取文件大小
     *
     * @param fileS 文件
     * @return {@link String}
     */
    public static String getFileSize(long fileS) {
        DecimalFormat df = new DecimalFormat("#0.0");
        String fileSizeString;
        if (fileS < 1073741824) {
            fileSizeString = df.format((double) fileS / 1048576) + "MB";
        } else {
            fileSizeString = df.format((double) fileS / 1073741824) + "GB";
        }
        return fileSizeString;
    }

    /**
     * 让声音路径
     *
     * @param context 上下文
     * @param url url
     * @return {@link String}
     */
    public static String getVoicePath(Context context, String url) {
        if (url.startsWith("/")) {
            return url;
        }

        String fileName = getFileName(url);
        String filePath = getVoiceDir(context) + File.separator + fileName;

        MLog.info(TAG, "getVoicePath fileName = " + fileName);
        MLog.info(TAG, "getVoicePath filePath = " + filePath);
        return filePath;
    }

    /**
     * 获取视频的路径
     *
     * @param context 上下文
     * @param url url
     * @return {@link String}
     */
    public static String getVideoPath(Context context, String url) {
        if (url.startsWith("/")) {
            return url;
        }

        String fileName = getFileName(url);
        String filePath = getVideoDir(context) + fileName;

        return filePath;
    }

    /**
     * 得到压缩视频路径
     *
     * @param context 上下文
     * @param sourcePath 源路径
     * @return {@link String}
     */
    public static String getCompressVideoPath(Context context, String sourcePath) {
        String compressFileName = getFileName(sourcePath);
        String compressPath = getCompressVideoDir(context) + compressFileName;
        return compressPath;
    }

    /**
     * 得到tmp文件名称
     *
     * @param fileName 文件名称
     * @return {@link String}
     */
    public static String getTmpFileName(String fileName) {
        String tmpName = fileName.substring(0, fileName.lastIndexOf(".")) + ".tmp";
        MLog.info(TAG, "tmpName = " + tmpName);
        return tmpName;
    }

    /**
     * 得到tmp文件路径
     *
     * @param context 上下文
     * @param url url
     * @return {@link String}
     */
    public static String getTmpFilePath(Context context, String url) {
        String fileName = getFileName(url);
        MLog.info("fileName = " + fileName);

        String tmpName = getTmpFileName(fileName);
        MLog.info("tmpName = " + tmpName);

        String tmpFilePath = FileUtils.getTmpDir(context, tmpName);
        MLog.info(TAG, "tmpFilePath = " + tmpFilePath);
        return tmpFilePath;
    }

    /**
     * 删除文件
     *
     * @param path 路径
     */
    public static void deleteFile(String path) {
        File file = new File(path);
        if (file.exists()) {
            boolean delete = file.delete();
        }
    }

    /**
     * 安全删除文件
     *
     * @param file 文件
     * @return boolean
     */
    public static boolean deleteFileSafely(File file) {
        MLog.info(TAG, "deleteFileSafely. ");

        if (file != null) {
            String tmpPath = file.getParent() + File.separator + System.currentTimeMillis();
            MLog.info(TAG, "tmpPath: " + tmpPath);
            File tmp = new File(tmpPath);
            boolean delete = false;
            if (file.renameTo(tmp)) {
                delete = tmp.delete();
            }
            return delete;
        }
        return false;
    }

    /**
     * 删除文件夹的文件
     *
     * @param filePath 文件路径
     */
    public static void deleteFolderFile(String filePath) {
    }

    /**
     * concat路径
     *
     * @param paths 路径
     * @return {@link String}
     */
    public static String concatPath(String... paths) {
        StringBuilder result = new StringBuilder();
        if (paths != null) {
            for (String path : paths) {
                setData(result, path);
            }
        }
        return result.toString();
    }

    private static void setData(StringBuilder result, String path) {
        if (path != null && path.length() > 0) {
            int len = result.length();
            boolean suffixSeparator = len > 0 && result.charAt(len - 1) == File.separatorChar; // 后缀是否是'/'
            boolean prefixSeparator = path.charAt(0) == File.separatorChar; // 前缀是否是'/'
            if (suffixSeparator && prefixSeparator) {
                result.append(path.substring(1));
            } else if (!suffixSeparator && !prefixSeparator) { // 补前缀
                result.append(File.separatorChar);
                result.append(path);
            } else {
                result.append(path);
            }
        }
    }

    /**
     * 让复制原始res sdcard路径
     *
     * @param context 上下文
     * @param rawResId 生res id
     * @param fileSuffix 文件后缀
     * @param fileCopyToPath 文件复制到路径
     * @return {@link String}
     */
    public static String getCopyRawResToSdcardPath(Context context, String rawResId, String fileSuffix, String fileCopyToPath) {
        String filePath = null;
        String fileDirPath = null;
        if (TextUtils.isEmpty(fileCopyToPath)) {
            filePath = getRootDir(context) + "/Video/video" + rawResId + fileSuffix;
        } else {
            filePath = getRootDir(context) + "/" + fileCopyToPath + "/video" + rawResId + fileSuffix;
            fileDirPath = getRootDir(context) + "/" + fileCopyToPath;
        }

        File file = new File(filePath);
        MLog.info("file = " + file.getPath());
        if (file.exists() && file.isFile()) {
            MLog.info("fileExists");
            return filePath;
        }

        if (!TextUtils.isEmpty(fileDirPath)) {
            File fileDir = new File(fileDirPath);
            if (!fileDir.exists()) {
                boolean mkdir = fileDir.mkdir();
            }
        }

        InputStream inputStream = null;
        FileOutputStream outputStream = null;
        try {
            int len;
            byte[] buffer = new byte[1024];
            inputStream = context.getResourceManager().getRawFileEntry(rawResId).openRawFile();
            outputStream = new FileOutputStream(file);
            while ((len = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }
            outputStream.flush();
            return filePath;
        } catch (IOException e) {
            MLog.error("getCopyRawResToSdcardPath: " + e.toString());
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                MLog.error("getCopyRawResToSdcardPath: " + e.getMessage());
            }
        }
        return filePath;
    }

    private void saveToFile(InputStream inStream, String filePath) {
        BufferedInputStream inputStream = null;
        BufferedOutputStream outputStream = null;
        try {
            inputStream = new BufferedInputStream(inStream);
            outputStream = new BufferedOutputStream(new FileOutputStream(filePath));
            int len = 0;
            while ((len = inputStream.read()) != -1) {
                outputStream.write(len);
            }
            outputStream.flush();
        } catch (IOException error) {
            MLog.error("saveToFile IOException " + error.getLocalizedMessage());
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.close();
                }

                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException error) {
                MLog.error("saveToFile finally IOException " + error.getLocalizedMessage());
            }
        }
    }
}
